#include "PolylineParser.h"

#include "LineDescGroupParser.h"
#include "PolyBeginParser.h"
#include "PolyStepParser.h"

#include <QXmlStreamReader>
#include <QString>

namespace Ipc2581b
{

PolylineParser::PolylineParser(
    PolyBeginParser *&_polyBeginParser
    , PolyStepParser *&_polyStepParser
    , LineDescGroupParser *&_lineDescGroupParser
):    m_polyBeginParser(_polyBeginParser)
    , m_polyStepParser(_polyStepParser)
    , m_lineDescGroupParser(_lineDescGroupParser)
{

}

bool PolylineParser::parse(QXmlStreamReader *reader)
{
    /* Pre */

    m_result.reset(new Polyline());

    /* Attributes */

    QStringRef data;

    /* Elements */

    while (reader->readNextStartElement())
    {
        auto name = reader->name();
        if (name == QStringLiteral("PolyBegin"))
        {
            if (!m_polyBeginParser->parse(reader))
                return false;
            auto result = m_polyBeginParser->result();
            m_result->polyBegin = result;
        }
        else if (m_polyStepParser->isSubstitution(name))
        {
            if (!m_polyStepParser->parse(reader))
                return false;
            auto result = m_polyStepParser->result();
            m_result->polyStepList.append(result);
        }
        else if (m_lineDescGroupParser->isSubstitution(name))
        {
            if (!m_lineDescGroupParser->parse(reader))
                return false;
            auto result = m_lineDescGroupParser->result();
            m_result->lineDescGroup = result;
        }
        else
            reader->skipCurrentElement();
    }

    /* Post */

    // TODO: Check multiplicity of elements/attributes

    return true;
}

Polyline *PolylineParser::result()
{
    return m_result.take();
}

}